/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
// 
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "utils.h"
#include <iostream>
#include <fstream>
#define MID_PREFIX "v2:"

namespace UTILS_NS
{
namespace PlatformUtils
{
	/**
	 * Create a machine ID for this machine and write it to the .PRODUCT_NAME file
	 * in the user runtime home directory. The machine id is specific to a particular
	 * user on a particular OS install and does not uniquely identify a machine.
	 */
	static std::string CreateMachineId(std::string& midFileName);
	static std::string GetOldMachineId(std::string& midFileName);
	static std::string ReadMIDFromFile(std::string& path);

	std::string GetFirstMACAddress()
	{
		NodeId id;
		try
		{
			PlatformUtils::GetNodeId(id);
		} catch(std::string e)
		{
			return e;
		}
		catch(...)
		{
			return "NoMACAddressFound";
		}
		char result[18];
		std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
			id[0],
			id[1],
			id[2],
			id[3],
			id[4],
			id[5]);
		return std::string(result);
	}

	std::string GetMachineId()
	{

		std::string midFileName(std::string(".") + PRODUCT_NAME);
		std::transform(midFileName.begin(), midFileName.end(), midFileName.begin(), tolower);

		std::string midFilePath(FileUtils::GetUserRuntimeHomeDirectory());
		midFilePath = FileUtils::Join(midFilePath.c_str(), midFileName.c_str(), NULL);
		std::string mid(ReadMIDFromFile(midFilePath));

		// If we couldn't read the MID or this is an old MID,
		// create a new one and return it.
		if (mid.empty() || mid.find(MID_PREFIX) != 0)
		{
			mid = CreateMachineId(midFileName);
		}

		return mid;
	}

	static std::string CreateMachineId(std::string& midFileName)
	{
		std::string newMID(MID_PREFIX);
		newMID.append(DataUtils::GenerateUUID());
		newMID.append("|");
		newMID.append(GetOldMachineId(midFileName));

		std::string midFilePath(FileUtils::GetUserRuntimeHomeDirectory());
		midFilePath = FileUtils::Join(midFilePath.c_str(), midFileName.c_str(), NULL);
		std::ofstream myfile;
		myfile.open(midFilePath.c_str());
		myfile << newMID << std::endl;
		myfile.close();

		return newMID;
	}

	static std::string GetOldMachineId(std::string& midFileName)
	{
		// Search for an old MID stored in a file
		std::vector<std::string> possibleMIDFiles;
		std::string path;
 		if (EnvironmentUtils::Has("KR_RUNTIME"))
		{
			path = EnvironmentUtils::Get("KR_RUNTIME");
			path = FileUtils::Join(path.c_str(), "..", "..", "..", midFileName.c_str(), NULL);
			possibleMIDFiles.push_back(path);
		}

		path = FileUtils::GetUserRuntimeHomeDirectory();
		path = FileUtils::Join(path.c_str(), midFileName.c_str(), NULL);
		possibleMIDFiles.push_back(path);

		path = FileUtils::GetSystemRuntimeHomeDirectory();
		path = FileUtils::Join(path.c_str(), midFileName.c_str(), NULL);
		possibleMIDFiles.push_back(path);

		std::string mid;
		for (size_t i = 0; i < possibleMIDFiles.size(); i++)
		{
			std::string& currentPath = possibleMIDFiles[i];
			mid = ReadMIDFromFile(currentPath);
			if (!mid.empty())
				return mid;
		}

		// Alternatively hash the MAC address and use that as the old MID
		std::string MACAddress(PlatformUtils::GetFirstMACAddress());
		return DataUtils::HexMD5(MACAddress);
	}

	static std::string ReadMIDFromFile(std::string& path)
	{
		if (FileUtils::IsFile(path))
		{
			std::ifstream file(path.c_str());
			if (!file.bad() && !file.fail() && ! file.eof())
			{
				std::string line;
				std::getline(file, line);
				line = FileUtils::Trim(line);
				file.close();
				return line;
			}
		}
		return std::string();
	}
}
}
